package com.xn2001.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局过滤器：
 * @Order(-1),标识该过滤器的执行顺序,值越小就越先执行
 * -----------------------------------------------------------
 * http://localhost:10010/user/1?authorization=admin
 * http://localhost:10010/order/101?authorization=admin
 */
@Order(-1)
@Component
public class LoginFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request、response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2.获取请求参数
        MultiValueMap<String, String> map = request.getQueryParams();
        String auth = map.getFirst("authorization");
        //3.判断请求参数中是否有：authorization
        if("admin".equals(auth)){
            return chain.filter(exchange);//放行请求
        }
        //设置状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();//拦截请求
    }
}
